package org.lan.heap;

import java.util.Arrays;

/**
 * @author <p><a href="mailto:1728209643@qq.com">XiaoSan</a>
 * @date 2019/11/23 10:12 AM
 */
public class Heap001 {

    public static void main(String[] args) {
        int[] arr = {9, 8, 5, 7, 6, 3, 2, 1};
        System.out.println(Arrays.toString(kMax(arr, 4)));
    }

    private static int[] kMax(int[] arr, int k) {
        for (int i = 0; i < k; i++) {
            build(arr, arr.length - i);
            swap(0, arr.length - i - 1, arr);
        }
        return Arrays.copyOfRange(arr, arr.length - k, arr.length);
    }

    private static int[] build(int[] arr) {
        return build(arr, arr.length);
    }

    private static int[] build(int[] arr, int len) {
        int start = len / 2 - 1;
        while (start != -1) {
            if (arr[start] < arr[2 * start + 1]) {
                swap(start, 2 * start + 1, arr);
            }
            if (2 * start + 2 < len && arr[start] < arr[2 * start + 2]) {
                swap(start, 2 * start + 2, arr);
            }
            start--;
        }
        return arr;
    }

    private static void swap(int i, int j, int[] arr) {
        int t = arr[j];
        arr[j] = arr[i];
        arr[i] = t;
    }
}
